//
//  NetVideoViewController.m
//  VLCPlayer
//
//  Created by mac on 2019/3/31.
//  Copyright © 2019 YangYang. All rights reserved.
//

#import "NetVideoViewController.h"
#import <AFNetworking.h>
#import "MRVLCPlayer.h"
#import "GetNetSpeed.h"

@interface NetVideoViewController ()

@property (nonatomic, strong) MRVLCPlayer *player;

@property (nonatomic, strong) UIImageView *downloadView;
@property (nonatomic, strong) UILabel *progressView;
@property (nonatomic, strong) NSMutableArray *downloadFiles;
@property (nonatomic, strong) NSString *downloadVideoPath;


@property (nonatomic, strong) VLCMediaPlayer *vlcPlayer;
@property (nonatomic, strong) VLCMedia *media;


@property (nonatomic, strong) CAShapeLayer *shapeLayer;
@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) GetNetSpeed *getNetSpeed;

@property (nonatomic, strong) UIButton *lastVideo;
@property (nonatomic, strong) UIButton *nextVideo;

@property (nonatomic, strong) VideoModel *currentPlayModel;


@end

@implementation NetVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    _currentPlayModel = self.videoArr[_videoIndex];
    _netVideoURL = _currentPlayModel.videoURL;
    
    NSLog(@"(编码前)网络视频播放f地址：%@",_netVideoURL);
    
    _getNetSpeed = [[GetNetSpeed alloc] init];
    
    [self createUI];
    
    [self createFolder];
    [self getAllFileNameFromFolder];
    NSLog(@"已下载文件：%@",self.downloadFiles);
    [self getVideoFile];
    NSLog(@"当前视频地址：%@",_downloadVideoPath);
}
#pragma mark ---------------------------------------创建目录--------------------------------------------
-(void)createFolder
{
    //获取Document文件
//    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSString * rarFilePath = [docsdir stringByAppendingPathComponent:@"DownloadVideoFiles"];//将需要创建的串拼接到后面
    
//    NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSAllDomainsMask, YES);
    
//    NSLog(@"_netVideoURL = %@",_netVideoURL);
    NSString *downFolder = DownloadFilePath(_currentPlayModel.downloadFolder);
    
//    NSLog(@"downFolder = %@",downFolder);
//    NSLog(@"rarFilePath = %@",rarFilePath);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:downFolder isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) ) {//如果文件夹不存在
        NSLog(@"文件夹不存在，创建文件夹");
        [fileManager createDirectoryAtPath:downFolder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
}

#pragma mark ---------------------------------------获取文件夹中的文件--------------------------------------------
-(void)getAllFileNameFromFolder
{
//    NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//    NSString *baseSavePath = [documentPath stringByAppendingPathComponent:@"DownloadVideoFiles"];
    NSString *baseSavePath = DownloadFilePath(_currentPlayModel.downloadFolder);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *myDirectoryEnumerator = [fileManager enumeratorAtPath:baseSavePath];  //baseSavePath 为文件夹的路径
    
    NSString *file;
    while((file=[myDirectoryEnumerator nextObject]))     //遍历当前目录
    {
        [self.downloadFiles addObject:@{@"fileName":[file stringByDeletingPathExtension],@"fileExtension":[file pathExtension],@"file":file}];
    }
}

-(void)getVideoFile
{
    NSString *videoExtension = [_netVideoURL pathExtension];
//    NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//    NSString *baseBundleSavePath = [appDir stringByAppendingPathComponent:@"DownloadVideoFiles"];
    NSString *baseBundleSavePath = DownloadFilePath(_currentPlayModel.downloadFolder);
    _downloadVideoPath = [NSBundle pathForResource:_netVideoName ofType:videoExtension inDirectory:baseBundleSavePath];
    
    
    
    if (_downloadVideoPath.length > 0) {
        _progressView.text = @"已下载";
        _shapeLayer.strokeEnd = 1.0;
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"清理文件" style:UIBarButtonItemStylePlain target:self action:@selector(clearFile)];
        
    }
    
    
}

-(void)clearFile
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:_downloadVideoPath isDirectory:&isDir];
    if (existed) {//如果文件夹存在
        NSLog(@"文件夹已经存在存在，清理文件夹");
        if ([fileManager removeItemAtPath:_downloadVideoPath error:nil]) {
            NSLog(@"清理成功");
            self.navigationItem.rightBarButtonItem = nil;
            _progressView.text = @"";
            _shapeLayer.strokeEnd = 0;
            _downloadVideoPath = @"";
//            [_shapeLayer removeFromSuperlayer];
//            _shapeLayer = nil;
        }
        else
        {
            NSLog(@"清理失败");
        }
    }
}

-(void)lastVideoAction
{
    if (_videoIndex > 0) {
        _videoIndex--;
        _currentPlayModel = self.videoArr[_videoIndex];
        _netVideoURL = _currentPlayModel.videoURL;
        self.navigationItem.title = _currentPlayModel.videoName;
        [self playVideoAction];
    }
}

-(void)nextVideoAction
{
    _videoIndex++;
    if (_videoIndex < self.videoArr.count) {
        _currentPlayModel = self.videoArr[_videoIndex];
        _netVideoURL = _currentPlayModel.videoURL;
        self.navigationItem.title = _currentPlayModel.videoName;
        [self playVideoAction];
    }
}

-(void)createUI
{
    UIButton *playAction = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:playAction];
    playAction.frame = CGRectMake(kScreenWidth / 2 - 50, 64 + 20, 100, 40);
    playAction.titleLabel.font = [UIFont systemFontOfSize:20];
    [playAction setTitle:@"播放" forState:UIControlStateNormal];
    [playAction setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [playAction addTarget:self action:@selector(playVideoAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    _lastVideo = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_lastVideo];
    [_lastVideo setTitle:@"上一集" forState:UIControlStateNormal];
    [_lastVideo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _lastVideo.frame = CGRectMake(kScreenWidth / 2- 50 - 20, kScreenHeight - 50 - 100, 100, 50);
    [_lastVideo addTarget:self action:@selector(lastVideoAction) forControlEvents:UIControlEventTouchUpInside];
    
    _nextVideo = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_nextVideo];
    [_nextVideo setTitle:@"下一集" forState:UIControlStateNormal];
    [_nextVideo setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _nextVideo.frame = CGRectMake(kScreenWidth / 2 + 20, kScreenHeight - 50 - 100, 100, 50);
    [_nextVideo addTarget:self action:@selector(nextVideoAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    _downloadView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"download"]];
    [self.view addSubview:_downloadView];
    _downloadView.frame = CGRectMake(kScreenWidth - 50 - 20, 64 + 20, 50, 50);
    _downloadView.userInteractionEnabled = YES;
    UITapGestureRecognizer *downloadGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(downloadGesture:)];
    [_downloadView addGestureRecognizer:downloadGesture];
    _downloadView.layer.cornerRadius = 25;
    
    
    _progressView = [[UILabel alloc] initWithFrame:CGRectMake(20, 64 + 20, 80, 80)];
    [self.view addSubview:_progressView];
    _progressView.numberOfLines = 0;
    _progressView.textColor = [UIColor blackColor];
    _progressView.textAlignment = NSTextAlignmentCenter;
    
    CGFloat width = 100;
    UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, width, width)];
    
    //第三步，用CAShapeLayer沿着第一步的路径画一个红色的环形进度条，但是起始点=终结点=0，所以开始不可见
    _shapeLayer = [CAShapeLayer layer];
    _shapeLayer.frame = CGRectMake(0, 0, width, width);
    _shapeLayer.position = _progressView.center;
    _shapeLayer.fillColor = [UIColor clearColor].CGColor;
    _shapeLayer.lineWidth = 10.f;
    _shapeLayer.strokeColor = [UIColor purpleColor].CGColor;
    _shapeLayer.strokeStart = 0;
    _shapeLayer.strokeEnd = 0;
    _shapeLayer.path = circle.CGPath;
    [self.view.layer addSublayer:_shapeLayer];
    
//    //第四步，用一个定时器进行测试，每一秒，进度加10%
//    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(animate) userInfo:nil repeats:YES];
    
    
}
-(void)animate{
    
//    [_getNetSpeed getInternetface];
    
    
//    _shapeLayer.strokeEnd += 0.01;
//    NSLog(@"_shapeLayer.strokeEnd = %lf",_shapeLayer.strokeEnd);
//    if (_shapeLayer.strokeEnd >= 1) {
//        [_timer invalidate];
//        _timer = nil;
//    }
}

-(void)downloadGesture:(UITapGestureRecognizer *)gesture
{
    if (_downloadVideoPath.length > 0) {
        NSLog(@"视频已被下载到本地");
    }
    else
    {
        [self download];
    }
}

- (void)WantToGoBackMianThread:(id)object{
    //需要在主线程执行的代码
//    NSLog(@"object:%@",object);
    NSNumber *progressObject = (NSNumber *)object;
    CGFloat progress = [progressObject floatValue];
    self.progressView.text = [NSString stringWithFormat:@"%.2lf%%\n%@",progress * 100,[_getNetSpeed getInternetface]];
    self.shapeLayer.strokeEnd = progress;
}

- (void)download{
//    [UIApplication sharedApplication].allow;
    __weak typeof(self) weakSelf = self;
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    NSString *videoURL = [_netVideoURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = videoURL;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSURLSessionDownloadTask *loadTask = [manger downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //下载进度监听
//        NSLog(@"Progress:----%lf",(downloadProgress.completedUnitCount * 1.0)/downloadProgress.totalUnitCount);
        CGFloat progress = (downloadProgress.completedUnitCount * 1.0)/downloadProgress.totalUnitCount;
        [weakSelf performSelectorOnMainThread:@selector(WantToGoBackMianThread:) withObject:[NSNumber numberWithFloat:progress] waitUntilDone:YES];
        
        
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        
        NSString *extensionName = response.suggestedFilename;
        NSArray *extensionArr = [extensionName componentsSeparatedByString:@"."];
        if (extensionArr.count > 0) {
            extensionName = [extensionArr lastObject];
        }
        else
        {
            extensionName = @"mp4";
        }
        NSString *fileName = weakSelf.netVideoName.length > 0 ? [NSString stringWithFormat:@"%@.%@",weakSelf.netVideoName,extensionName] : response.suggestedFilename;
        
//         NSString *fileName = response.suggestedFilename;
        
//        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"DownloadVideoFiles/%@",fileName]];
        
        NSString *downloadFilePath = [NSString stringWithFormat:@"%@/%@",weakSelf.currentPlayModel.downloadFolder,fileName];
        NSString *fullPath = DownloadFilePath(downloadFilePath);
        
        NSLog(@"fullPath:%@",fullPath);
        NSLog(@"targetPath:%@",targetPath);
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"filePath:%@",filePath);
        [self getVideoFile];
    }];
    [loadTask resume];
}

-(void)playVideoAction
{
//    _netVideoName = [_netVideoName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *mediaURL;
    if (_downloadVideoPath.length > 0) {
        NSLog(@"文件已下载，播放本地视频");
        NSURL *url = [NSURL fileURLWithPath:_downloadVideoPath];
        
        self.player.mediaURL = url;
        [self.player showInView:self.view.window];
        
//        _media = [[VLCMedia alloc] initWithURL:url];
//        self.vlcPlayer.drawable = self.view;
//        self.vlcPlayer.media = _media;
//        [self.vlcPlayer play];
    }
    else
    {
        NSString *videoURL = [_netVideoURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        mediaURL = [NSURL URLWithString:videoURL];
        NSLog(@"(编码后)网络视频播放地址：%@",videoURL);
        self.player.mediaURL = mediaURL;
        [self.player showInView:self.view.window];
    }

}

-(MRVLCPlayer *)player
{
    if (!_player) {
        _player = [[MRVLCPlayer alloc] init];
        _player.bounds = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width / 16 * 9);
        _player.center = self.view.center;
    }
    return _player;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_player dismiss];
}

-(NSMutableArray *)downloadFiles
{
    if (!_downloadFiles) {
        _downloadFiles = [NSMutableArray new];
    }
    return _downloadFiles;
}

-(VLCMediaPlayer *)vlcPlayer
{
    if (!_vlcPlayer) {
        _vlcPlayer = [[VLCMediaPlayer alloc] init];
        _vlcPlayer.delegate = self;
    }
    return _vlcPlayer;
}

-(void)dealloc
{
    NSLog(@"销毁网络视频播放控制器");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
